package com.zztl.infiniteBand.util

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo

/**
 * @desc
 * @auth ${user}
 * @time 2018/6/26  11:37
 */
object NetworkUtil {
    val TYPE_NONE = -1
    val TYPE_MOBILE = 0
    val TYPE_WIFI = 1

    /**
     * 判断当前网络是否可用
     *
     * @return
     */
    // 判断当前网络状态是否为连接状态
    val isNetworkAvailable: Boolean
        get() {
            val cm = UiUtils.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

            val networkInfo = cm.allNetworkInfo
            if (networkInfo != null && networkInfo.size > 0) {
                for (i in networkInfo.indices) {
                    if (networkInfo[i].state == NetworkInfo.State.CONNECTED) {
                        return true
                    }
                }
            }

            return false
        }

    /**
     * 获取网络状态
     *
     * @param context
     * @return one of TYPE_NONE, TYPE_MOBILE, TYPE_WIFI
     * @permission android.permission.ACCESS_NETWORK_STATE
     */
    fun getNetWorkStates(context: Context): Int {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        if (activeNetworkInfo == null || !activeNetworkInfo.isConnected) {
            return TYPE_NONE//没网
        }

        val type = activeNetworkInfo.type
        when (type) {
            ConnectivityManager.TYPE_MOBILE -> return TYPE_MOBILE//移动数据
            ConnectivityManager.TYPE_WIFI -> return TYPE_WIFI//WIFI
            else -> {
            }
        }
        return TYPE_NONE
    }

}
